import {Dialog} from 'vant';
export const websocket = {
    data() {
        return {
            ws: null,
            timeout: 500000,
            Offtimeout:5000,
            timeoutObj: null,
            serverTimeoutObj: null,
            message:'',
        }
    },

    methods: {
        initWebSocket(UserId) { //初始化weosocket
            const wsuri = 'ws://' + window.location.host + '/socketServer/' + UserId ;
            this.ws = new WebSocket(wsuri);
            this.ws.onmessage = this.websocketOnmessage;
            this.ws.onopen = this.websocketOnopen;
            this.ws.onerror = this.websocketOnerror;
            this.ws.onclose = this.websocketClose;
        },
        websocketOnopen() { //连接建立之后执行send方法发送数据
            console.log(this.getNowTime(new Date) + " Socket 已打开");
            //心跳检测重置
            this.start();
        },
        websocketOnerror() {//连接建立失败重连

            this.initWebSocket();
        },
        websocketOnmessage(e) { //一级数据接收

            console.log(e.data)
            const data = JSON.parse(e.data);
            //处理服务器返回发生消息成功或失败的方法
            this.onMessageServer(data);

            //刷新心跳设置，重写 websocketOnmessage(e)方法必须调用此方法，否则时间过长websocket连接会断开
            this.start()
            return data;
        },
        websocketSend(data) {//数据发送
            this.ws.send(JSON.stringify(data))
        },
        websocketClose(e) {  //关闭
            console.log('断开连接', e);
        },
        start() {//刷新心跳设置
            const that = this;
            console.log(this.getNowTime(new Date) + " Socket 心跳检测");
            this.timeoutObj && clearTimeout(this.timeoutObj);
            this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
            this.timeoutObj = setTimeout(function () {
                //这里发送一个心跳，后端收到后，返回一个心跳消息，
                //onmessage拿到返回的心跳就说明连接正常
                console.log(that.getNowTime(new Date) + ' Socket 连接重试');
                const socketMsg = {type: '21', message: "连接成功"};
                that.ws.send(JSON.stringify(socketMsg));
                that.serverTimeoutObj = setTimeout(function () {
                    console.log(this.ws);
                    that.ws.close();
                }, that.Offtimeout);
            }, that.timeout)
        },
        p(s) {
            return s < 10 ? '0' + s : s;
        },
        //获取当前时间（年月日时分秒）
        getNowTime(dates) {
            const myDate = dates;
            //获取当前年
            const year = myDate.getFullYear();
            //获取当前月
            const month = myDate.getMonth() + 1;
            //获取当前日
            const date = myDate.getDate();
            const h = myDate.getHours();       //获取当前小时数(0-23)
            const m = myDate.getMinutes();     //获取当前分钟数(0-59)
            const s = myDate.getSeconds();
            return year + '-' + this.p(month) + "-" + this.p(date) + " " + this.p(h) + ':' + this.p(m) + ":" + this.p(s);
        },
        onMessageServer(data){//处理服务器返回发生消息成功或失败的方法
            if (data.type === '404') {
                Dialog.confirm({
                    title: '标题',
                    message: 'PC用户不在线'
                }).then(() => {

                }).catch(() => {

                });
            }
            if (data.type === '200') {
                Dialog.confirm({
                    title: '标题',
                    message: '扫码发送成功'
                }).then(() => {

                }).catch(() => {

                });
            }
        },

    }

}